<template>
  <el-drawer 
    v-model="visible" 
    :title="isEdit ? '编辑管理员' : '添加管理员'" 
    direction="rtl" 
    size="520px"
    :before-close="handleClose"
    class="premium-drawer"
  >
    <!-- 自定义头部 -->
    <template #header="{ titleId, titleClass }">
      <div class="drawer-header">
        <div class="header-icon">
          <el-icon size="24">
            <Avatar v-if="isEdit" />
            <UserFilled v-else />
          </el-icon>
        </div>
        <div class="header-content">
          <h3 :id="titleId" :class="titleClass">
            {{ isEdit ? '编辑管理员' : '添加管理员' }}
          </h3>
          <p class="header-subtitle">
            {{ isEdit ? '修改管理员信息' : '创建新的管理员账户' }}
          </p>
        </div>
      </div>
    </template>

    <div class="drawer-content">
      <el-form 
        ref="formRef" 
        :model="formData" 
        :rules="formRules" 
        label-width="100px" 
        label-position="top"
        class="premium-form"
      >
        <!-- 头像上传（未来功能） -->
        <!-- <el-form-item label="头像" class="avatar-form-item">
          <div class="avatar-upload-container">
            <div class="avatar-preview">
              <el-upload 
                class="avatar-uploader" 
                action="#" 
                :show-file-list="false" 
                :auto-upload="false"
                :on-change="handleAvatarChange" 
                accept="image/*"
              >
                <img v-if="formData.avatar" :src="formData.avatar" class="avatar-img" />
                <div v-else class="avatar-placeholder">
                  <el-icon size="32"><Plus /></el-icon>
                </div>
              </el-upload>
            </div>
            <div class="avatar-tips">
              <p>点击上传头像</p>
              <p>支持jpg、png格式，大小不超过2MB</p>
            </div>
          </div>
        </el-form-item> -->

        <!-- 基本信息字段 -->
        <div class="form-grid">
          <el-form-item label="姓名" prop="name" class="form-item">
            <el-input 
              v-model="formData.name" 
              placeholder="请输入管理员姓名"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email" class="form-item">
            <el-input 
              v-model="formData.email" 
              placeholder="请输入邮箱地址"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><Message /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>

        <div class="form-grid">
          <el-form-item label="部门" prop="department" class="form-item">
            <el-select 
              v-model="formData.department" 
              placeholder="请选择部门" 
              style="width: 100%"
              class="premium-select"
              clearable
            >
              <template #prefix>
                <el-icon><OfficeBuilding /></el-icon>
              </template>
              <el-option 
                v-for="dept in departmentOptions" 
                :key="dept.value" 
                :label="dept.label" 
                :value="dept.value" 
              />
            </el-select>
          </el-form-item>

          <el-form-item label="手机号" prop="phone" class="form-item">
            <el-input 
              v-model="formData.phone" 
              placeholder="请输入手机号"
              class="premium-input"
              clearable
            >
              <template #prefix>
                <el-icon><Phone /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </div>

        <el-form-item label="工号" prop="employeeId" class="form-item full-width">
          <el-input 
            v-model="formData.employeeId" 
            placeholder="请输入工号"
            class="premium-input"
            clearable
          >
            <template #prefix>
              <el-icon><CreditCard /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 新增时的密码和状态设置 -->
        <template v-if="!isEdit">
          <!-- 分隔线 -->
          <div class="form-divider">
            <div class="divider-line"></div>
            <div class="divider-text">
              <el-icon><Lock /></el-icon>
              安全设置
            </div>
            <div class="divider-line"></div>
          </div>

          <div class="form-grid">
            <el-form-item label="登录密码" prop="password" class="form-item">
              <el-input 
                v-model="formData.password" 
                type="password" 
                placeholder="请输入登录密码"
                class="premium-input"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword" class="form-item">
              <el-input 
                v-model="formData.confirmPassword" 
                type="password" 
                placeholder="请再次输入密码"
                class="premium-input"
                show-password
                clearable
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>

          <el-form-item label="账户状态" prop="status" class="form-item full-width">
            <el-radio-group v-model="formData.status" class="premium-radio-group">
              <el-radio value="正常" class="premium-radio">
                <span class="radio-content">
                  <el-icon class="radio-icon success"><Select /></el-icon>
                  正常
                </span>
              </el-radio>
              <el-radio value="禁用" class="premium-radio">
                <span class="radio-content">
                  <el-icon class="radio-icon danger"><CloseBold /></el-icon>
                  禁用
                </span>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button 
          @click="handleClose"
          class="cancel-btn"
          size="large"
        >
          取消
        </el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitting"
          class="submit-btn"
          size="large"
        >
          <el-icon v-if="!submitting">
            <Check v-if="isEdit" />
            <Plus v-else />
          </el-icon>
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, Message, OfficeBuilding, Phone, CreditCard, 
  Lock, Select, CloseBold, Check, Plus, Avatar, UserFilled 
} from '@element-plus/icons-vue'
import { postJson, put, get } from '@/axios'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  adminData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const submitting = ref(false)

// 部门选项
const departmentOptions = [
  { label: '技术部', value: '技术部' },
  { label: '运营部', value: '运营部' },
  { label: '教务部', value: '教务部' },
  { label: '市场部', value: '市场部' },
  { label: '人事部', value: '人事部' }
]

// 表单数据
const defaultFormData = {
  id: null,
  name: '',
  email: '',
  department: '',
  phone: '',
  employeeId: '',
  password: '',
  confirmPassword: '',
  status: '正常',
  remark: ''
}

const formData = reactive({ ...defaultFormData })

// 计算属性
const visible = computed({
  get() {
    return props.visible
  },
  set(value) {
    emit('update:visible', value)
  }
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 重置表单数据
    Object.assign(formData, defaultFormData);

    // 编辑模式：填充数据
    if (props.isEdit && props.adminData) {
      Object.assign(formData, {
        ...props.adminData,
        status: props.adminData.status === '正常' ? '正常' : '禁用',
      })
      formData.password = ''
      formData.confirmPassword = ''
    }

    nextTick(() => formRef.value?.clearValidate());
  }
});

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入管理员姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
    { validator: check, message: '该邮箱已经被使用', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
    { validator: check, message: '该手机号已经被使用', trigger: 'blur' }
  ],
  employeeId: [
    { required: true, message: '请输入工号', trigger: 'blur' },
    { validator: check, message: '该工号已经被使用', trigger: 'blur' }
  ],
  status: [
    { required: !props.isEdit, message: '请选择账户状态', trigger: 'change' }
  ],
  password: [
    {
      required: !props.isEdit,
      message: '请输入登录密码',
      trigger: 'blur'
    },
    { min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    {
      required: !props.isEdit,
      message: '请再次输入密码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 提交处理
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    const submitData = {
      ...formData,
      status: formData.status === '正常'
    }

    let response
    if (props.isEdit) {
      delete submitData.password
      delete submitData.confirmPassword
      delete submitData.status
      response = await put(`/umsAdmin/update`, submitData)
    } else {
      delete submitData.confirmPassword
      response = await postJson('/umsAdmin/save', submitData)
    }

    if (response && (response.code === 200 || (typeof response === 'object' && response.hasOwnProperty('code') && response.code === 200))) {
      ElMessage.success(props.isEdit ? '更新成功' : '新增成功')
      emit('submit')
      handleClose()
    } else if (typeof response === 'object' && response !== null) {
      if (response.message && typeof response.message === 'object') {
        handleUniqueConstraintErrors(response.message)
      } else {
        const errorMsg = response.message || '操作失败'
        ElMessage.error(errorMsg)
      }
    } else {
      ElMessage.success(props.isEdit ? '更新成功' : '新增成功')
      emit('submit')
      handleClose()
    }
  } catch (error) {
    console.error('提交失败:', error)
    handleError(error.response?.data || error)
  } finally {
    submitting.value = false
  }
}

// 错误处理函数
const handleError = (errorData) => {
  if (!errorData) {
    ElMessage.error('操作失败')
    return
  }

  if (errorData.message && typeof errorData.message === 'object') {
    handleUniqueConstraintErrors(errorData.message)
  } else if (typeof errorData.message === 'string') {
    handleUniqueConstraintError(errorData.message)
  } else if (typeof errorData === 'object' && !Array.isArray(errorData)) {
    handleUniqueConstraintErrors(errorData)
  } else {
    ElMessage.error(errorData.message || '操作失败')
  }
}

const handleUniqueConstraintErrors = (errors) => {
  Object.keys(errors).forEach(fieldName => {
    setFieldError(fieldName, errors[fieldName])
  })
}

const handleUniqueConstraintError = (errorMessage) => {
  if (errorMessage.includes('邮箱')) {
    setFieldError('email', errorMessage)
  } else if (errorMessage.includes('手机号')) {
    setFieldError('phone', errorMessage)
  } else if (errorMessage.includes('工号')) {
    setFieldError('employeeId', errorMessage)
  } else {
    ElMessage.error(errorMessage)
  }
}

const setFieldError = (fieldName, errorMessage) => {
  nextTick(() => {
    formRef.value.clearValidate([fieldName])
    formRef.value.validateField(fieldName, () => {
      const field = formRef.value.fields.find(field => field.prop === fieldName)
      if (field) {
        field.validateState = 'error'
        field.validateMessage = errorMessage
      }
    })
  })
}

function check(rule, value, callback) {
  get('/umsAdmin/checkUnique', { id: formData.id, value, field: rule.field }, content => {
    if (content) {
      callback()
    } else {
      callback(new Error())
    }
  })
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped lang="scss">
.premium-drawer {
  :deep(.el-drawer) {
    background: white;
    box-shadow: -10px 0 30px rgba(0, 0, 0, 0.1);
  }

  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 0;
    border-bottom: none;
  }

  :deep(.el-drawer__title) {
    display: none;
  }

  :deep(.el-drawer__body) {
    padding: 0;
    display: flex;
    flex-direction: column;
  }
}

.drawer-header {
  display: flex;
  align-items: center;
  padding: 24px 24px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 100px;
    height: 100px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    transform: translate(30px, -30px);
  }

  .header-icon {
    width: 56px;
    height: 56px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.3);
  }

  .header-content {
    h3 {
      margin: 0 0 4px 0;
      font-size: 20px;
      font-weight: 600;
      color: white;
    }

    .header-subtitle {
      margin: 0;
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

.drawer-content {
  flex: 1;
  padding: 32px 24px 24px;
  overflow-y: auto;
  background: white;

  // 自定义滚动条
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f3f4;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #667eea, #764ba2);
    border-radius: 3px;

    &:hover {
      background: linear-gradient(135deg, #5a67d8, #6b46c1);
    }
  }
}

.premium-form {
  .form-section {
    background: white;
    border-radius: 20px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    position: relative;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4px;
      background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
      transition: all 0.3s ease;
    }

    .section-header {
      display: flex;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #e5e7eb;

      .section-icon {
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        margin-right: 12px;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);

        &.security {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          box-shadow: 0 4px 12px rgba(245, 87, 108, 0.3);
        }
      }

      .section-title {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;
      }
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-item {
    &.full-width {
      grid-column: 1 / -1;
    }

    :deep(.el-form-item__label) {
      font-weight: 600;
      color: #374151;
      font-size: 14px;
      margin-bottom: 8px;
    }

    :deep(.el-form-item__content) {
      line-height: 1;
    }
  }

  .premium-input {
    :deep(.el-input__wrapper) {
      background: #f8fafc;
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      padding: 12px 16px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);

      &:hover {
        border-color: #cbd5e1;
        background: white;
      }

      &.is-focus {
        border-color: #667eea;
        background: white;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
      }
    }

    :deep(.el-input__inner) {
      font-size: 14px;
      color: #1f2937;

      &::placeholder {
        color: #9ca3af;
      }
    }

    :deep(.el-input__prefix) {
      color: #6b7280;
    }
  }

  .premium-select {
    :deep(.el-select__wrapper) {
      background: #f8fafc;
      border: 2px solid #e2e8f0;
      border-radius: 12px;
      padding: 12px 16px;
      transition: all 0.3s ease;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);

      &:hover {
        border-color: #cbd5e1;
        background: white;
      }

      &.is-focus {
        border-color: #667eea;
        background: white;
        box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
      }
    }

    :deep(.el-select__placeholder) {
      color: #9ca3af;
    }

    :deep(.el-select__prefix) {
      color: #6b7280;
    }
  }

  .premium-radio-group {
    display: flex;
    gap: 24px;

    .premium-radio {
      :deep(.el-radio__input) {
        .el-radio__inner {
          width: 18px;
          height: 18px;
          border: 2px solid #d1d5db;
          border-radius: 50%;

          &:hover {
            border-color: #667eea;
          }
        }

        &.is-checked .el-radio__inner {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border-color: #667eea;

          &::after {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: white;
          }
        }
      }

      :deep(.el-radio__label) {
        font-size: 0;
      }

      .radio-content {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        font-weight: 500;
        color: #374151;

        .radio-icon {
          &.success {
            color: #10b981;
          }

          &.danger {
            color: #ef4444;
          }
        }
      }
    }
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 24px;
  background: white;
  border-top: 1px solid #e5e7eb;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);

  .cancel-btn {
    :deep(.el-button) {
      background: #f3f4f6;
      border: 2px solid #e5e7eb;
      color: #6b7280;
      border-radius: 12px;
      padding: 12px 24px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        background: #e5e7eb;
        border-color: #d1d5db;
        color: #374151;
        transform: translateY(-1px);
      }
    }
  }

  .submit-btn {
    :deep(.el-button) {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      border-radius: 12px;
      padding: 12px 24px;
      font-weight: 500;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
      transition: all 0.3s ease;

      &:hover {
        background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
      }

      &:active {
        transform: translateY(0);
      }

      .el-icon {
        margin-right: 8px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .drawer-content {
    padding: 24px 16px 16px;
  }

  .premium-form {
    .form-grid {
      grid-template-columns: 1fr;
      gap: 16px;
    }

    .form-divider {
      margin: 24px 0 20px 0;

      .divider-text {
        padding: 0 12px;
        font-size: 13px;
        height: 32px;
        min-width: 100px;
      }
    }
  }

  .drawer-footer {
    padding: 20px 16px;
    
    .cancel-btn,
    .submit-btn {
      :deep(.el-button) {
        padding: 10px 20px;
      }
    }
  }
}

// 动画效果
@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

.premium-form {
  animation: slideInRight 0.4s ease;
}
</style>